using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
using UnityEngine.AI;


//[DisableAutoCreation]
//public partial class FollowTargetSystem : SystemBase
//{
//    protected override void OnCreate()
//    {
//        RequireForUpdate<PlayerTag>();
//        RequireForUpdate<EnemyTag>();
//    }

//    protected override void OnUpdate()
//    {
//        Entity target = SystemAPI.GetSingletonEntity<PlayerTag>();

//        FollowTargetSystemJob followTargetSystemJob = new FollowTargetSystemJob() { transform = SystemAPI.GetComponent<LocalTransform>(target) };
//        followTargetSystemJob.ScheduleParallel();
//    }

//    [BurstCompile]
//    [WithAll(typeof(EnemyTag))]
//    partial struct FollowTargetSystemJob : IJobEntity
//    {
//        public LocalTransform transform;
//        //写用ref,读用in
//        public void Execute(ref LocalTransform localTransform, ref VelComp velComp)
//        {
//            var targetPos = transform.Position;
//            var selfPos = localTransform.Position;
//            var dir = (targetPos - selfPos);
//            var dirVector = new Vector3(dir.x, dir.y, dir.z);
//            dirVector = dirVector.normalized;
//            //移动
//            velComp.value = new float2(dirVector.x, dirVector.y) * 4;
//        }
//    }
//}
[DisableAutoCreation]
public partial struct FollowTargetSystem : ISystem
{
    [BurstCompile]
    public void OnCreate(ref SystemState state)
    {
        state.RequireForUpdate<PlayerTag>();
        state.RequireForUpdate<EnemyTag>();
    }

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        Entity target = SystemAPI.GetSingletonEntity<PlayerTag>();

        foreach ((MoveAspect moveAspect, Entity e) in SystemAPI.Query<MoveAspect>().WithAll<EnemyTag>().WithEntityAccess())
        {
            var targetPos = SystemAPI.GetComponent<LocalTransform>(target).Position;
            var selfPos = moveAspect.transform.ValueRO.Position;
            var dir = (targetPos - selfPos);
            var dirVector = new float3(dir.x, dir.y, dir.z);
            dirVector = dirVector.normalized();
            //移动
            SystemAPI.SetComponent<VelComp>(e, new() { value = new float2(dirVector.x, dirVector.y) * 2 });

        }
    }

}